<?php

namespace common\behaviors;

use Yii;
use yii\base\Behavior;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;

class UploadFileBehavior extends Behavior
{
    public static $UPLOADS_DIR = 'uploads';

    public $param = [];
    public $model;

    public function uploadFile()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $this->param = Yii::$app->request->getBodyParams();

        $modelClass = new $this->model;
        $fileInstance = UploadedFile::getInstance($modelClass, $this->param['file']);

        if (!empty($fileInstance)) {
            $file = self::getUploadPath($this->param['dir']) . DIRECTORY_SEPARATOR . self::getFileName($fileInstance);
            $fileInstance->saveAs($file);
            $param = [
                'error' => $fileInstance->error,
                'name' => $fileInstance->name,
                'size' => $fileInstance->size,
                'tempName' => $fileInstance->tempName,
                'type' => $fileInstance->type,
                'link' => self::getLink($file),
            ];
            if ($fileInstance->error === 0) {
                return ['result' => 'success', 'message' => Yii::t('app', 'Success'), 'data' => $param];
            }
        }

        throw new \Exception(Yii::t('app', 'Error'));
    }

    static function getUploadPath($dir)
    {
        $uploadPath = Yii::getAlias('@public') . DIRECTORY_SEPARATOR . self::$UPLOADS_DIR . ($dir ? DIRECTORY_SEPARATOR . $dir : '');
        if (!FileHelper::createDirectory($uploadPath, 0777)) {
            throw new \Exception('Cannot create "' . $uploadPath . '". Please check write permissions.');
        }
        return $uploadPath;
    }

    static function getLink($fileName)
    {
        return str_replace('\\', '/', str_replace(Yii::getAlias('@public'), '', $fileName));
    }

    static function getFileName($fileInstanse, $namePostfix = true)
    {
        $baseName = str_ireplace('.' . $fileInstanse->extension, '', $fileInstanse->name);
        $fileName = StringHelper::truncate(Inflector::slug($baseName), 32, '');
        if ($namePostfix || !$fileName) {
            $fileName .= ($fileName ? '-' : '') . substr(uniqid(md5(rand()), true), 0, 10);
        }
        $fileName .= '.' . $fileInstanse->extension;

        return $fileName;
    }
}